package com.dk.service.impl;

import com.dk.mapper.AjaxUserMapper;
import com.dk.mapper.UserRoleMapper;
import com.dk.pojo.AjaxUser;
import com.dk.service.UserService;
import com.dk.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private AjaxUserMapper ajaxUserMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public Integer loginInfo(AjaxUser user, HttpServletRequest request) {
       AjaxUser u =  ajaxUserMapper.loginInfo(user.getUname());
       if(u == null){
           return 1;
       }
       if (u.getFlag()>=3) {
           return 2;
       }
        try {
            if (!MD5Utils.validPassword(user.getPassword(),u.getPassword())){
               ajaxUserMapper.updateByName(u.getUname(),u.getFlag()+1);
               return 3;
           }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (u.getFlag()>0){
           ajaxUserMapper.updateByName(u.getUname(),0);
       }
        HttpSession session = request.getSession();
        session.setAttribute("loginUser",u);
       return 4;
    }

    @Override
    public Boolean selectcheckPhone(String uname) {
        AjaxUser u = ajaxUserMapper.selectByName(uname);
        return u == null ? true :false;
    }

    @Override
    public int deleteById(Integer uid) {
        ajaxUserMapper.deleteByPrimaryKey(uid);
        return userRoleMapper.deleteByKey(uid);
    }

    @Override
    public AjaxUser selectById(Integer uid) {
        return ajaxUserMapper.selectByPrimaryKey(uid);
    }

    @Override
    public boolean insertInfo(AjaxUser user, Integer[] rids) {
        String pwd = "120";
        try {
            pwd = MD5Utils.getEncryptedPwd(pwd);
            user.setPassword(pwd);
            //增加用户表
            ajaxUserMapper.insertInfo(user);
            //增加用户角色表
            userRoleMapper.insertBatch(rids,user.getUid());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    @Override
    public List<AjaxUser> getInfo() {
        return ajaxUserMapper.selectByExample(null);
    }

    @Override
    public Integer insertRe(AjaxUser user) {
        try {
            user.setPassword(MD5Utils.getEncryptedPwd(user.getPassword()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ajaxUserMapper.insertSelective(user);
    }

}
